package com.mashibing.apidriver.service;

import com.mashibing.apidriver.remote.ServiceDriverUserClient;
import com.mashibing.apidriver.remote.ServiceVerificationCodeClient;
import com.mashibing.internalcommon.constant.CommonStatusEnum;
import com.mashibing.internalcommon.constant.IdentityConstants;
import com.mashibing.internalcommon.dto.ResponseResult;
import com.mashibing.internalcommon.request.VerificationCodeDTO;
import com.mashibing.internalcommon.response.DriverUserExistsResponse;
import com.mashibing.internalcommon.response.NumberCodeResponse;
import com.mashibing.internalcommon.response.TokenResponse;
import com.mashibing.internalcommon.util.JwtUtils;
import com.mashibing.internalcommon.util.RedisPrefixUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.concurrent.TimeUnit;

import static com.mashibing.internalcommon.constant.IdentityConstants.DRIVER_IDENTITY;
import static com.mashibing.internalcommon.constant.IdentityConstants.PASSENGER_IDENTITY;
import static com.mashibing.internalcommon.constant.TokenConstants.ACCESS_TOKEN_TYPE;
import static com.mashibing.internalcommon.constant.TokenConstants.REFRESH_TOKEN_TYPE;

/**
 * @author 史慕尧
 */
@Service
@Slf4j
public class VerificationCodeService {
    @Autowired
    ServiceDriverUserClient serviceDriverUserClient;
    @Autowired
    ServiceVerificationCodeClient serviceVerificationCodeClient;
    @Autowired
    StringRedisTemplate stringRedisTemplate;


    public ResponseResult checkAndSengVerificationCode(String driverPhone) {
//查询手机是否存在,并获取手机号
        ResponseResult<DriverUserExistsResponse> driverUserExistsResponseResponseResult = serviceDriverUserClient.checkDriver(driverPhone);
        String driverPhone1 = driverUserExistsResponseResponseResult.getData().getDriverPhone();
        int isExists = driverUserExistsResponseResponseResult.getData().getIfExists();
        log.info("获取的手机号：" + driverPhone1);
        if (isExists == 0) {
            return ResponseResult.fail(CommonStatusEnum.DRIVER_NOT_EXITST.getCode(), CommonStatusEnum.DRIVER_NOT_EXITST.getValue());
        }
        //获取验证码
        ResponseResult<NumberCodeResponse> numberCodeResult = serviceVerificationCodeClient.getNumberCode(8);
        NumberCodeResponse numberCodeResponse = numberCodeResult.getData();
        int numberCode = numberCodeResponse.getNumberCode();
        log.info("获取的验证码：" + numberCode);
        // 调用第三方发生验证码,第三方：阿里短信服务，腾讯，华信，容联(最后联调)
        // 存入redis。1：key，2：存入value
        String key = RedisPrefixUtils.generatorKeyByPhone(driverPhone, IdentityConstants.DRIVER_IDENTITY);
        log.info("key:"+key+"value:"+driverPhone);
       stringRedisTemplate.opsForValue().set(key,numberCode+"",2, TimeUnit.MINUTES);
        return ResponseResult.success();
    }


    public ResponseResult checkCode(String driverPhone, String verificationCode) {
//根据redis读取验证码
        //生成key
        String key = RedisPrefixUtils.generatorKeyByPhone(driverPhone,DRIVER_IDENTITY);
        //根据key获取value
        String codeRedis = stringRedisTemplate.opsForValue().get(key);
        System.out.println("redis中的value" + codeRedis);
// 校验验证码
        if (StringUtils.isBlank(codeRedis)) {
            return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode(), CommonStatusEnum.VERIFICATION_CODE_ERROR.getValue());
        }
        if (!verificationCode.trim().equals(codeRedis.trim())) {
            return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode(), CommonStatusEnum.VERIFICATION_CODE_ERROR.getValue());
        }

        //颁发令牌
        String accessToken = JwtUtils.generatorToken(driverPhone, DRIVER_IDENTITY,ACCESS_TOKEN_TYPE);
        String refreshToken = JwtUtils.generatorToken(driverPhone, DRIVER_IDENTITY,REFRESH_TOKEN_TYPE);
//token存储到redis中
        String accessTokenKey = RedisPrefixUtils.generatorTokenKey(driverPhone, DRIVER_IDENTITY, ACCESS_TOKEN_TYPE);
        stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 30, TimeUnit.DAYS);
//        stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 10, TimeUnit.SECONDS);

        String refreshTokenKey = RedisPrefixUtils.generatorTokenKey(driverPhone, DRIVER_IDENTITY, REFRESH_TOKEN_TYPE);
        stringRedisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 31, TimeUnit.DAYS);
//        stringRedisTemplate.opsForValue().set(refreshTokenKey, accessToken, 51, TimeUnit.SECONDS);

        // 响应
        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setRefreshToken(refreshToken);
        return ResponseResult.success(tokenResponse);

    }
}
